# import qiniuyun
from django.conf import settings
from django.contrib.auth import login, logout
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import JsonResponse, HttpResponse
import json,re,logging

from django_redis import get_redis_connection
# from libs.qiniuyun import put_data
from houses.models import House
from iHome.utils.views import LoginRequiredMixin
from users.qiniu import upload_avatar
from users.utils import checkIdcard
from .models import User
from django import http

logger = logging.getLogger('django')
# -----我的发布的房源展示-----
class UserHouse(LoginRequiredMixin,View):
    def get(self,request):
        # 1.获取当前用户的房屋信息
        try:
            houses = House.objects.filter(user=request.user)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': 400, 'errmsg': "查询数据失败"})
        # 2.创建空列表
        house_dict_list = []
        # 3.遍历
        for house in houses:
            house_dict = {
                'address':House.address,
                'area_name':House.area.name,
                'ctime': House.create_time.strftime("%Y-%m-%d"),
                'house_id':House.id,
                'img_url': House.index_image_url,
                'order_count': House.order_count,
                'price': House.price,
                'room_count': House.room_count,
                'title':House.title,
                'user_avatar': House.user.avatar_url,
            }
            house_dict_list.append(house_dict)
        return http.JsonResponse({'errno': 0, 'errmsg': "OK", 'data': house_dict_list})






#---- 用户注册------
class RegisterView(View):
    def post(self,request):
        # 1.接受参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get("mobile")
        phonecode = json_dict.get("phonecode")
        password = json_dict.get("password")
        password2 = json_dict.get('password2')
        # 2.校验参数
        # 判断参数是否完整
        if not all([mobile, phonecode, password, password2]):
            return http.JsonResponse({'errno': 4103, 'errmsg': "参数不全"})

        # 判断密码是否一致
        if password != password2:
            return http.JsonResponse({'errno': 4106, 'errmsg': "密码不一致"})

        # 2. 从redis中获取指定手机号对应的短信验证码的
        redis_conn = get_redis_connection('verify_code')
        try:
            sms_code = redis_conn.get("SMS_" + mobile)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': 4001, 'errmsg': "获取本地验证码失败"})

        if not sms_code:
            return http.JsonResponse({'errno': 4002, 'errmsg': "短信验证码过期"})

        # 3. 校验验证码
        if phonecode != sms_code.decode():
            return http.JsonResponse({'errno': 4004, 'errmsg': "短信验证码错误"})

        # 4. 初始化 user 模型，并设置数据并添加到数据库
        try:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': 4102, 'errmsg': "用户创建失败"})

        # 状态保持
        login(request, user)
        return http.JsonResponse({'errno': 0, 'errmsg': "注册成功"})



'''用户登录'''
class Login(View):
    '''用户登录'''

    def post(self,request):
        '''用户登录'''
        # 1. 获取参数值和判断是否有值
        data_dict = json.loads(request.body.decode())

        mobile = data_dict.get("mobile")
        password = data_dict.get("password")

        if not all([mobile, password]):
            return http,JsonResponse({'errno': 4103, 'errmsg': "参数不全"})
        # 2.从数据库查询指定用户
        try:
            user = User.objects.get(mobile=mobile)

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': 4104, 'errmsg': "用户不存在"})
        # 3.校验密码
        if not user.check_password(password):
            return http.JsonResponse({'errno': 4106, 'errmsg': "密码错误"})

        # 4.保存用户状态
        login(request, user)

        # 5.返回登录结果
        return http.JsonResponse({'errno': 0, 'errmsg': "登录成功"})

'''用户状态查询'''
class Session(View):
    '''用户状态查询'''

    def get(self, request):
        '''检测用户是否已经登录'''

        user = request.user

        if user.is_authenticated:
            data = {'user_id': user.id, 'name': user.username}
            return http.JsonResponse({'error': 0, 'errmsg': '用户已登录', 'data': data})
        else:
            return http.JsonResponse({'errno': 4101, 'errmsg': '用户未登录'})


'''用户退出'''
class Logout(LoginRequiredMixin,View):
    '''用户退出'''
    def delete(self, request):
        '''清楚保存的信息'''

        # 清除session
        logout(request)
        return http,JsonResponse({'errno': 0, 'errmsg': "用户已退出"})




from django.contrib.auth import login, authenticate
# 用户中心  王荣桓
class UserInfoView(LoginRequiredMixin, View):

    def get(self, request):

        dict = {
            "avatar_url": str(request.user.avatar),
            "create_time": request.user.date_joined,
            "mobile": request.user.mobile,
            "name": request.user.username,
            "user_id": int(request.user.id)

        }

        return JsonResponse({'data': dict,
                             'errno': 0,
                             'errmsg': 'ok'})


# 上传头像 王荣桓
class AvatarView(LoginRequiredMixin, View):
    def post(self, request):
        avatar = request.FILES.get('avatar')
        if not avatar:
            return JsonResponse({'errno': 4302,
                                 'errmsg': '文件读写错误'})
        file_data = avatar.read()

        key = upload_avatar(file_data)

        try:
            User.objects.filter(username=request.user.username).update(avatar=settings.QINIU_BUCKET_URL +'/'+ key)
            print(type(request.user.avatar))
            print(request.user.avatar)
        except Exception as e:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '数据错误'})
        # 返回token,key必须为uptoken
        dict = {
            'avatar_url': settings.QINIU_BUCKET_URL + key
        }
        return JsonResponse({'data': dict,
                              'errmsg': '头像上传成功',
                              'errno': 0})


class UserAuthView(View):

    def post(self, request):
        dict = json.loads(request.body.decode())
        real_name = dict.get('real_name')
        id_card = dict.get('id_card')

        if not all([real_name, id_card]):
            return JsonResponse({'errno': 4103,
                                 'errmsg': '缺少必传参数'})

        id_card = checkIdcard(id_card)

        try:
            request.user.real_name = real_name
            request.user.id_card = id_card
            request.user.save()
        except Exception as e:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '数据库存储失败'})

        return JsonResponse({'errno': 0,
                             'errmsg': 'ok'})

    def get(self, request):

        data = {
            "real_name": request.user.real_name,
            "id_card": request.user.id_card
        }

        return JsonResponse({'errno': 0,
                             'errmsg': 'ok',
                             'data': data})
